package com.jrx.anytxn.transaction.timer.job.coupon.config;

import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.customer.entity.CmCustomerExtInfo;
import com.jrx.anytxn.param.entity.PrActivityInfo;
import com.jrx.anytxn.param.service.rights.IPrActivityInfoService;
import com.jrx.anytxn.transaction.timer.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.timer.config.CouponConfig;
import com.jrx.anytxn.transaction.timer.job.coupon.dto.CustomerRightsDTO;
import com.jrx.anytxn.transaction.timer.job.coupon.step.CouponSharingProcessor;
import com.jrx.anytxn.transaction.timer.job.coupon.step.CouponSharingWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName CouponSharingConfiguration
 *
 * @author lujianyou
 * @version 1.0
 * @description 分享消费送权益
 * @date 2021/12/24 10:52
 **/
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
@EnableBatchProcessing
@Slf4j
public class CouponSharingConfiguration {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private CouponSharingProcessor sharingProcessor;
    @Autowired
    private CouponSharingWriter sharingWriter;
    @Autowired
    private CouponConfig couponConfig;
    @Autowired
    private IPrActivityInfoService activityInfoService;

    @Bean
    public Job couponSharingJob() {
        return jobBuilderFactory.get("couponSharingJob").incrementer(new RunIdIncrementer()).start(couponSharingStep())
            .build();
    }

    @Bean
    public Step couponSharingStep() {
        return stepBuilderFactory.get("couponSharingStep")
            .<CmCustomerExtInfo, CustomerRightsDTO>chunk(anytxnBatchProperties.getDefaultConfig().getChunkLimit())
            // 表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
            .reader(couponSharingReader()).processor(sharingProcessor).writer(sharingWriter)
            .transactionManager(platformTransactionManager).taskExecutor(new SimpleAsyncTaskExecutor())
            // 多线程
            .throttleLimit(anytxnBatchProperties.getDefaultConfig().getThrottleLimit()).build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<CmCustomerExtInfo> couponSharingReader() {
        // 校验活动的有效性
        Map<String, Object> map = new HashMap<>(8);
        try {
            PrActivityInfo prActivityInfo = activityInfoService.checkAllActivityInfo(Constants.DEFAULT_TENANT_ID,
                    couponConfig.getActivity().getNewUserSharedConsumeFirstActivityId(), Constants.DEFAULT_PRODTCT_CODE);
            map.put("tenantId", Constants.DEFAULT_TENANT_ID);
            map.put("effectiveDate", prActivityInfo.getEffectiveDate());
            map.put("expireDate", prActivityInfo.getExpireDate());
            map.put("productId", "XIBXAH000001");
        } catch (TxnBizException e) {
            log.info("活动信息异常，异常原因：{}", e.getErrMsg());
            // 不存在的租户id，防止NullBean，reader 不允许为空
            map.put("tenantId", "102");
        }

        MyBatisCursorItemReader<CmCustomerExtInfo> itemStreamReader = new MyBatisCursorItemReader<>();
        itemStreamReader.setSaveState(false);
        itemStreamReader.setSqlSessionFactory(sqlSessionFactory);
        // 查询方法
        itemStreamReader.setQueryId("com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerExtInfoMapper." + "selectByRecommenderCodeNotNull");

        // 查询参数设置
        itemStreamReader.setParameterValues(map);

        SynchronizedItemStreamReader<CmCustomerExtInfo> synchronizedItemStreamReader =
            new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(itemStreamReader);
        return synchronizedItemStreamReader;
    }

}
